package mbp.tests;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import mbp.core.Resource;
import mbp.logger.LoggerProxy;

import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.behaviours.TickerBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;

/**
 * 
 * @author Wojciech Wilanski
 *
 */
public class ReceiverAgent extends Agent
{
	List<Resource> rs;
	
	@Override
    protected void setup()
    {
        System.out.println("[ReceiverAgent] LocalName: " + getAID().getLocalName());
        
        rs = Collections.synchronizedList(new ArrayList<Resource>());
        MsgReader msgReader = new MsgReader();
        ResourceChecker rChecker = new ResourceChecker(this, 1000);
        
        
        addBehaviour(msgReader);
        addBehaviour(rChecker);
        
        //f(1) = 3;
    }
	
	public int f(int a)
	{
		return 0;
	}
	
	public class MsgReader extends CyclicBehaviour
	{

		@Override
		public void action() 
		{
			ACLMessage msg = myAgent.receive();
			
			if(msg != null)
			{
				LoggerProxy.logReceiving(msg, myAgent);
				//MessageTemplate mt = MessageTemplate.MatchPerformative(ACLMessage.CFP);
				if(msg.getPerformative() == ACLMessage.CFP)
				{
					try 
					{
						Resource resource = (Resource)msg.getContentObject();
						System.out.println("[ReceiverAgent] LocalName: " + getAID().getLocalName() + "Recieved Resource...");
						resource.printResourceInfo();
						
						rs.add(resource);
						//System.out.println("Resource Type name : " + resource.GetType().GetStoreTypeName());
						//System.out.println("Resource Owner     : " + resource.GetOwner());
					} 
					catch (UnreadableException e) 
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			else
			{
				block();
			}
			
		}

		
		
	}
	
	public class ResourceChecker extends TickerBehaviour
	{

		public ResourceChecker(Agent a, long period) {
			super(a, period);
		}

		@Override
		protected void onTick() 
		{
			if(rs.size()==0)return;
			
			Iterator<Resource> it = rs.iterator();
			
			System.out.println("*** STORAGE ***");
			while(it.hasNext())
			{
				Resource rc = (Resource)it.next();
				
				if(!rc.isValid())
				{
					it.remove();
					continue;
				}
				
				rc.printResourceInfo();
			}
			
			System.out.println("*** END *** Resources count: " + rs.size());
			
		}

		
	}

}
